package com.example.cms.Schedules;
import com.example.cms.DB.DBUtil;
import com.example.cms.Users.User;
import java.sql.*;
import java.sql.Date;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;

public class SchedulesManager {
    private Scanner scanner;
    private User currentUser;
    // 日期时间格式化器
    private DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

    public  SchedulesManager() {
        this.scanner = new Scanner(System.in);


    }
    // ==================== 排班管理 ====================
    public void showScheduleMenu() {
        while (true) {
            System.out.println("\n--- 排班管理 ---");
            System.out.println("1. 创建排班");
            System.out.println("2. 查看排班");
            System.out.println("3. 修改排班");
            System.out.println("4. 查看医生排班");
            System.out.println("0. 返回主菜单");

            System.out.print("请选择操作: ");
            String choice = scanner.nextLine();

            switch (choice) {
                case "1":
                    createSchedule();
                    break;
                case "2":
                    viewSchedule();
                    break;
                case "3":
                    updateSchedule();
                    break;
                case "4":
                    viewDoctorSchedules();
                    break;
                case "0":
                    return;
                default:
                    System.out.println("无效选择，请重新输入！");
            }
        }
    }

    private void createSchedule() {
        System.out.println("\n--- 创建排班 ---");
        try {
            System.out.print("医生ID: ");
            int doctorId = Integer.parseInt(scanner.nextLine());

            System.out.print("排班日期(YYYY-MM-DD): ");
            LocalDate scheduleDate = LocalDate.parse(scanner.nextLine(), dateFormatter);

            System.out.print("时间段(如: 上午/下午/晚上): ");
            String timeSlot = scanner.nextLine();

            System.out.print("总号源数: ");
            int totalSlots = Integer.parseInt(scanner.nextLine());

            System.out.print("诊室号: ");
            String roomNumber = scanner.nextLine();

            System.out.print("诊费: ");
            double fee = Double.parseDouble(scanner.nextLine());

            Schedule schedule = new Schedule(doctorId, scheduleDate, timeSlot);
            schedule.setTotalSlots(totalSlots);
            schedule.setRoomNumber(roomNumber);
            schedule.setFee(fee);

            if (addSchedule(schedule)) {
                System.out.println("排班创建成功！");
            } else {
                System.out.println("排班创建失败！");
            }
        } catch (Exception e) {
            System.out.println("创建失败: " + e.getMessage());
        }
    }

    private void viewSchedule() {
        System.out.println("\n--- 查看排班 ---");
        System.out.print("请输入排班ID: ");
        int scheduleId = Integer.parseInt(scanner.nextLine());

        try {
            Schedule schedule = findScheduleById(scheduleId);
            if (schedule != null) {
                displayScheduleInfo(schedule);
            } else {
                System.out.println("未找到排班信息！");
            }
        } catch (Exception e) {
            System.out.println("查询失败: " + e.getMessage());
        }
    }

    private void updateSchedule() {
        System.out.println("\n--- 修改排班 ---");
        System.out.print("请输入排班ID: ");
        int scheduleId = Integer.parseInt(scanner.nextLine());

        try {
            Schedule schedule = findScheduleById(scheduleId);
            if (schedule == null) {
                System.out.println("排班不存在！");
                return;
            }

            displayScheduleInfo(schedule);
            System.out.println("\n请输入要修改的信息(留空保持不变):");

            System.out.print("总号源数[" + schedule.getTotalSlots() + "]: ");
            String totalSlotsStr = scanner.nextLine();
            if (!totalSlotsStr.isEmpty()) schedule.setTotalSlots(Integer.parseInt(totalSlotsStr));

            System.out.print("诊室号[" + schedule.getRoomNumber() + "]: ");
            String roomNumber = scanner.nextLine();
            if (!roomNumber.isEmpty()) schedule.setRoomNumber(roomNumber);

            System.out.print("诊费[" + schedule.getFee() + "]: ");
            String feeStr = scanner.nextLine();
            if (!feeStr.isEmpty()) schedule.setFee(Double.parseDouble(feeStr));

            if (updateScheduleInDB(schedule)) {
                System.out.println("排班信息更新成功！");
            } else {
                System.out.println("排班信息更新失败！");
            }
        } catch (Exception e) {
            System.out.println("修改失败: " + e.getMessage());
        }
    }

    private void viewDoctorSchedules() {
        System.out.println("\n--- 查看医生排班 ---");
        System.out.print("请输入医生ID: ");
        int doctorId = Integer.parseInt(scanner.nextLine());

        try {
            List<Schedule> schedules = getSchedulesByDoctor(doctorId);
            if (schedules.isEmpty()) {
                System.out.println("该医生暂无排班");
                return;
            }

            System.out.println("排班ID\t日期\t时间段\t诊室\t总号源\t可用\t状态");
            System.out.println("----------------------------------------------------------------");
            for (Schedule schedule : schedules) {
                System.out.printf("%d\t%s\t%s\t%s\t%d\t%d\t%s\n",
                        schedule.getScheduleId(),
                        schedule.getScheduleDate(),
                        schedule.getTimeSlot(),
                        schedule.getRoomNumber(),
                        schedule.getTotalSlots(),
                        schedule.getAvailableSlots(),
                        schedule.getStatus());
            }
        } catch (Exception e) {
            System.out.println("获取排班失败: " + e.getMessage());
        }
    }

    private void displayScheduleInfo(Schedule schedule) {
        System.out.println("\n=== 排班信息 ===");
        System.out.println("排班ID: " + schedule.getScheduleId());
        System.out.println("医生: " + schedule.getDoctorName());
        System.out.println("科室: " + schedule.getDepartmentName());
        System.out.println("日期: " + schedule.getScheduleDate());
        System.out.println("时间段: " + schedule.getTimeSlot());
        System.out.println("总号源: " + schedule.getTotalSlots());
        System.out.println("已预约: " + schedule.getBookedSlots());
        System.out.println("可用号源: " + schedule.getAvailableSlots());
        System.out.println("诊室: " + schedule.getRoomNumber());
        System.out.println("诊费: " + schedule.getFee());
        System.out.println("状态: " + schedule.getStatus());
    }


    // 排班相关操作方法
    public boolean addSchedule(Schedule schedule) {
        String sql = "INSERT INTO schedules (doctor_id, schedule_date, time_slot, total_slots, " +
                "room_number, fee) VALUES (?, ?, ?, ?, ?, ?)";

        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {
            pstmt.setInt(1, schedule.getDoctorId());
            pstmt.setDate(2, Date.valueOf(schedule.getScheduleDate()));
            pstmt.setString(3, schedule.getTimeSlot());
            pstmt.setInt(4, schedule.getTotalSlots());
            pstmt.setString(5, schedule.getRoomNumber());
            pstmt.setDouble(6, schedule.getFee());

            int affectedRows = pstmt.executeUpdate();
            if (affectedRows > 0) {
                try (ResultSet rs = pstmt.getGeneratedKeys()) {
                    if (rs.next()) {
                        schedule.setScheduleId(rs.getInt(1));
                    }
                }
                return true;
            }
        } catch (SQLException e) {
            System.err.println("添加排班失败: " + e.getMessage());
        }
        return false;
    }

    public Schedule findScheduleById(int scheduleId) {
        String sql = "SELECT s.*, d.name as doctor_name, dept.dept_name " +
                "FROM schedules s " +
                "JOIN doctors d ON s.doctor_id = d.doctor_id " +
                "JOIN departments dept ON d.department_id = dept.department_id " +
                "WHERE s.schedule_id = ?";

        try (   Connection conn = DBUtil.getConnection();
                PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setInt(1, scheduleId);
            try (ResultSet rs = pstmt.executeQuery()) {
                if (rs.next()) {
                    return mapResultSetToSchedule(rs);
                }
            }
        } catch (SQLException e) {
            System.err.println("查询排班失败: " + e.getMessage());
        }
        return null;
    }

    private boolean updateScheduleInDB(Schedule schedule) {
        String sql = "UPDATE schedules SET doctor_id = ?, schedule_date = ?, time_slot = ?, " +
                "total_slots = ?, room_number = ?, fee = ? " +
                "WHERE schedule_id = ?";

        try (   Connection conn = DBUtil.getConnection();
                PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setInt(1, schedule.getDoctorId());
            pstmt.setDate(2, Date.valueOf(schedule.getScheduleDate()));
            pstmt.setString(3, schedule.getTimeSlot());
            pstmt.setInt(4, schedule.getTotalSlots());
            pstmt.setString(5, schedule.getRoomNumber());
            pstmt.setDouble(6, schedule.getFee());
            pstmt.setInt(7, schedule.getScheduleId());

            return pstmt.executeUpdate() > 0;
        } catch (SQLException e) {
            System.err.println("更新排班失败: " + e.getMessage());
        }
        return false;
    }

    private List<Schedule> getSchedulesByDoctor(int doctorId) {
        List<Schedule> schedules = new ArrayList<>();
        String sql = "SELECT s.*, d.name as doctor_name, dept.dept_name " +
                "FROM schedules s " +
                "JOIN doctors d ON s.doctor_id = d.doctor_id " +
                "JOIN departments dept ON d.department_id = dept.department_id " +
                "WHERE s.doctor_id = ? AND s.schedule_date >= CURDATE() " +
                "ORDER BY s.schedule_date, s.time_slot";

        try (   Connection conn = DBUtil.getConnection();
                PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setInt(1, doctorId);
            try (ResultSet rs = pstmt.executeQuery()) {
                while (rs.next()) {
                    schedules.add(mapResultSetToSchedule(rs));
                }
            }
        } catch (SQLException e) {
            System.err.println("获取医生排班失败: " + e.getMessage());
        }
        return schedules;

    }





    private Schedule mapResultSetToSchedule(ResultSet rs) throws SQLException {
        Schedule schedule = new Schedule();
        schedule.setScheduleId(rs.getInt("schedule_id"));
        schedule.setDoctorId(rs.getInt("doctor_id"));
        schedule.setScheduleDate(rs.getDate("schedule_date").toLocalDate());
        schedule.setTimeSlot(rs.getString("time_slot"));
        schedule.setTotalSlots(rs.getInt("total_slots"));
        schedule.setBookedSlots(rs.getInt("booked_slots"));
        schedule.setAvailableSlots(rs.getInt("available_slots"));
        schedule.setStatus(rs.getString("status"));
        schedule.setRoomNumber(rs.getString("room_number"));
        schedule.setFee(rs.getDouble("fee"));
        // 额外信息
        schedule.setDoctorName(rs.getString("doctor_name"));
        schedule.setDepartmentName(rs.getString("dept_name"));
        return schedule;
    }
    public void setCurrentUser(User currentUser) {
        this.currentUser = currentUser;
    }

}
